import React, { useEffect, useRef, useState } from 'react';
import { List, Avatar, Typography, Badge, Skeleton, Empty } from 'antd';
import { UserOutlined } from '@ant-design/icons';
import MessageItem from './MessageItem';
import { SvgIcon } from '@/components/icon';
import { ChatItem } from '@/types/chat';
import { useThrottleFn, useUpdateLayoutEffect, useSize, useScroll, useKeyPress } from 'ahooks';
import RecommendCards from './RecommendCards';
import { useContextSelector } from 'use-context-selector';
import { ChatContext } from '../context';
import useWindowWidth from '@/hooks/event/use-window-width';
import { useLinkParams, useChatRecordLoading } from '@/store/configStore';

interface ChatListProps {
  messages: ChatItem[];
  robotAvatar: string;
  username?: string;
  colorPrimary: string;
  isMetaHuman?: boolean;
  isAudioPlaying?: boolean;
  isMuted?: boolean;
  isMessageSend?: boolean;
  isInputTyping?: boolean;
  deleteMessage?: (index: number) => void;
  reFreshAnswer?: (index: number) => void;
  handleSend: (message: string) => void;
  emitCard?: () => void;
  isChat?: boolean;
  guessQuestions?: { id: string; content: string }[];
  onQuestionClick?: (question: string) => void;
}

const ChatList = ({
  messages,
  robotAvatar,
  username,
  colorPrimary,
  isMetaHuman,
  isAudioPlaying,
  isMuted,
  isMessageSend,
  isInputTyping,
  deleteMessage,
  handleSend,
  reFreshAnswer,
  emitCard,
  isChat = true,
  guessQuestions,
  onQuestionClick,
}: ChatListProps) => {
  const chatListRef = useRef<HTMLDivElement>(null);
  const [hideItem, setHideItem] = useState(false);
  const [isUserScrolling, setIsUserScrolling] = useState(false);
  const { isPc } = useWindowWidth();
  const linkParams = useLinkParams();
  const chatRecordLoading = useChatRecordLoading();

  const { run } = useThrottleFn(
    () => {
      if (!isUserScrolling && chatListRef.current) {
        chatListRef.current.scrollTop = chatListRef.current.scrollHeight;
      }
    },
    { wait: 25 },
  );

  // 监听滚动事件
  useEffect(() => {
    const handleScroll = () => {
      if (chatListRef.current) {
        const atBottom =
          chatListRef.current.scrollTop + chatListRef.current.clientHeight >=
          chatListRef.current.scrollHeight - 50;
        setIsUserScrolling(!atBottom);
      }
    };

    const chatListElement = chatListRef.current;

    if (chatListElement) {
      chatListElement.addEventListener('scroll', handleScroll);
    }

    return () => {
      if (chatListElement) {
        chatListElement.removeEventListener('scroll', handleScroll);
      }
    };
  }, []);

  useEffect(() => {
    // console.log('触发几次', isMessageSend);

    if (isMessageSend == true) {
      setIsUserScrolling(false);
    }
    // run();
    setHideItem(isMessageSend ?? false);
  }, [isMessageSend]);

  useUpdateLayoutEffect(() => {
    if (!isUserScrolling) {
      run();
    }
  }, [messages]);

  // 最后一个消息大小变化后触发滚动到最后
  const scrollToBottom = () => {
    run();
  };

  return (
    <div
      ref={chatListRef}
      className={`hide-scrollbar flex-1 overflow-y-auto px-2 ${isPc && 'py-4'}`}
      style={!isPc ? { marginBottom: '0px' } : undefined}
    >
      {/* {messages.length === 0 &&
        (isChat && !linkParams?.chat_id ? (
          <>
            <Empty description={<Typography.Text>我是AI应用助手，欢迎向我提问~</Typography.Text>} />
            <RecommendCards  emitCard={emitCard}/>   
          </>
        ) : (
          <>
            <div className="flex justify-end" style={{ padding: '20px 0' }}>
              <Skeleton.Input active={true} block={false} />
            </div>
            <div className="flex justify-start">
              <Skeleton active paragraph={{ rows: 5 }} />
            </div>
            <div className="flex justify-end" style={{ padding: '20px 0' }}>
              <Skeleton.Input active={true} block={false} />
            </div>
            <div className="flex justify-start">
              <Skeleton active paragraph={{ rows: 5 }} />
            </div>
          </>
        ))} */}
      {messages.length === 0 && (!isChat || chatRecordLoading) && (
        <>
          <div className="flex justify-end" style={{ padding: '20px 0' }}>
            <Skeleton.Input active={true} block={false} />
          </div>
          <div className="flex justify-start">
            <Skeleton active paragraph={{ rows: 5 }} />
          </div>
          <div className="flex justify-end" style={{ padding: '20px 0' }}>
            <Skeleton.Input active={true} block={false} />
          </div>
          <div className="flex justify-start">
            <Skeleton active paragraph={{ rows: 5 }} />
          </div>
        </>
      )}
      {messages.length > 0 && (
        <List
          itemLayout="horizontal"
          split={false}
          dataSource={messages}
          renderItem={(item, index) => (
            <List.Item>
              <div
                className={`flex w-full flex-col ${item.isUser ? 'justify-end' : 'justify-start'}`}
              >
                {!item.isUser && (
                  <div className="flex items-center">
                    {/* <Avatar src={robotAvatar} className="mr-2 h-10 w-10 flex-shrink-0" /> */}
                    {/* <SvgIcon icon="ic_rj_robot" size="40" /> */}
                    <div className="ml-2 font-bold">
                      {item.loading &&
                        (item?.loadingText ? (
                          <div id="answer">
                            {/* <Badge status="processing" color="#985ae1" text="AI回答中..." /> */}
                            <SvgIcon icon="ic_rj_loading" color="#6640FF" size="20" />
                            <span style={{ color: '#6640FF', paddingLeft: '10px' }}>
                              AI回答中...
                            </span>
                          </div>
                        ) : (
                          <div id="think">
                            {/* <Badge status="processing" color="#985ae1" text="AI思考中..." /> */}
                            <SvgIcon icon="ic_rj_loading" color="#6640FF" size="20" />
                            <span style={{ color: '#6640FF', paddingLeft: '10px' }}>
                              AI思考中...
                            </span>
                          </div>
                        ))}
                    </div>
                  </div>
                )}
                {true ? (
                  <MessageItem
                    key={index}
                    item={item}
                    index={index}
                    isMessageSend={isMessageSend}
                    hideItem={hideItem}
                    handleSend={handleSend}
                    isLastOne={index === messages.length - 1}
                    scrollToBottom={scrollToBottom}
                    deleteMessage={deleteMessage}
                    reFreshAnswer={reFreshAnswer}
                    guessQuestions={guessQuestions}
                    onQuestionClick={onQuestionClick}
                  ></MessageItem>
                ) : (
                  <div>
                    <Skeleton.Input
                      active
                      className="mt-1 w-full"
                      style={{
                        background: item.isUser ? '#E7E1FF' : '#F3F4F9',
                        borderRadius: item.isUser ? '10px 0px 10px 10px' : '0px 10px 10px 10px',
                      }}
                    />
                  </div>
                )}
              </div>
            </List.Item>
          )}
        />
      )}
    </div>
  );
};

export default React.memo(ChatList);
